#!/bin/gawk -f
#
# Extracts a record or a data item from a dbas file.
# Not interactive because server in Heidelberg can not use it.

BEGIN {
#	if ( FILENAME == "-" ) {
# print "usage: qdbext_non_int -v b=BLOCK_NAME -v i=ITEM file"
# print "hdr: flag for printing of header [optional]"
# print "   hdr=none: header is not printed"
# print "   default: header is printed"
# print "i: item [optional]"
# exit( 1 )
#	}

	hdr="none"
	block = toupper( b )
	if ( block == "" ) {
	    printf "ERROR no block given\n"
	    exit(1)
	}

	do_item = ( i != "" )
	if ( do_item ) {
		itm = toupper( i )
		if ( hdr == "" ) print "# " block " " itm
	}
	
	inblock = 0
	count = 0
	blockcount = 0
	ident = "NULL_IDENT"
}

function out(   nrec, nitm, iitm, i) {
	if ( !do_item ) {
		if ( id == "show" ) print ident " "
		if ( id == "ident" ) print "$ IDENT " ident
		for ( i=1; i<= count; i++ ) {
			if ( hdr == "none" ) {
				if ( match( line[i], /^\$/ ) ) {
					split( line[i], descr )
					if ( descr[2] == "TABLE" ) i++
					continue
				}
				if ( i == count ) continue
			}
			print line[i]
		}
	}
	else {
		split( line[2], descr )
		nrec = descr[4]
		if ( descr[2] == "TEXT" ) {
			sub( /\$ TEXT */, "", line[2] )
			if ( id == "show" ) printf ident " "
			if ( id == "ident" ) print "$ IDENT " ident
			print line[2]
		}
		else if ( descr[2] == "LIST" ) {
			if ( id == "ident" ) print "$ IDENT " ident
			if ( 3+nrec == count-1 ) {
				for ( i=3; i<3+nrec; i++ ) {
					split( line[i], data )
					if ( toupper( data[1] ) == itm ) {
						sub( data[1]" *", "", line[i] )
						if ( id == "show" ) printf ident " "
						print line[i]
					}
				}
			}
			else {
				print "INCONSISTENT NUMBER OF RECORDS" 
			}
		}
		else if ( descr[2] == "TABLE" ) {
			if ( id == "ident" ) print "$ IDENT " ident
			nitm = descr[6]
			if ( 4+nrec == count-1 ) {
				split( line[3], headr )
				for ( i=1; i<= nitm; i++ ) {
					if ( toupper( headr[i] ) == itm ) iitm = i
				}
				for ( i=4; i<4+nrec; i++ ) {
					split( line[i], data )
					if ( id == "show" ) printf ident " "
					print data[iitm]
				}
			}
			else {
				print "INCONSISTENT NUMBER OF RECORDS" 
			}
		}
		else {
		    print "ILLEGAL LINE:", line[2]
		}
	}
}

$2 == "IDENT" {
	ident = $3
	next
}

$2 == "DATA" {
	blockcount++
	if ( numblock ) {
		if ( blockcount != block ) {
			inblock = 0
			next
		}
		inblock = 1
		line[++count] = $0
		next
	}
	if ( toupper( $3 ) !~ block ) {
		inblock = 0
		next
	}
	inblock = 1
	line[++count] = $0
	next
}

$2 == "END" {
	if ( !inblock ) next
	line[++count] = $0
	line[++count] = ""
	out()
# allow for multiple occurrences of same data block
	count = 0
	inblock = 0
	next
}

!inblock { next }

{ 
    if ( do_item && $2 == "REMARK" ) next
    line[++count] = $0 
}
